<template>
  <el-alert :title="title" :type="types" center show-icon v-if="showalret" />
  <div>
    <!-- 使用 v-for 循环渲染每一页的卡片 -->
    <div v-for="(row, index) in cardRows" :key="index" class="card-row">
      <el-card
          v-for="(foodItem, foodIndex) in row"
          :key="foodIndex"
          class="card-item"
          shadow="hover"
      >
        <template #header>
          <h2>{{ foodItem.description }}</h2>
        </template>
        <img :src="foodItem.imageUrl" class="card-img" />
        <p class="card-price">¥: {{ foodItem.allprice }}</p>
        <div>
          <el-input-number v-model="foodItem.ammount" :min="1" :max="10" :disabled=true></el-input-number>
          <el-button type="warning" round @click="itemdetail(foodItem)">详情</el-button>
          <el-button type="danger" round @click="placeOrder(foodItem)">立即购买</el-button>
        </div>

      </el-card>
    </div>
    <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        v-model:currentPage="currentPage"
        class="mt-4"
    />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed,} from "vue";
import {getfoodservice, getmenupackservice, insertorderdetailByitempackservice} from "@/api/food.js";
import {userorder} from "@/api/food.js";
import {useRouter} from "vue-router";
const types=ref('warning')
const title=ref('');
const showalret=ref(false);
const type = ref('海鲜');
const items = reactive([]);
const pageSize = 8; // 每页显示的卡片数量
const currentPage = ref(1); // 当前页数
const routers=useRouter();
const subject=ref('顾客')
const orderno=ref(1);
const getFood = async () => {
  try {
    const response = await getmenupackservice();
    if (response.code === 200) {
      console.log("执行成功");
      console.log(response);
      items.splice(0, items.length); // 清空原有数据
      response.date.forEach(item => {
        item.ammount = 1;
        items.push(item);
      });
    }
  } catch (error) {
    console.log("执行失败", error);
  }
};

onMounted(() => {
  getFood(); // 在组件挂载时调用获取食物的方法
  generateOrderNumber()
});

// 计算当前页的卡片数据
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return items.slice(startIndex, endIndex);
});

// 计算总卡片数量
const totalItems = computed(() => items.length);

// 将卡片数据分割成每行四个的数组
const cardRows = computed(() => {
  const rows = [];
  for (let i = 0; i < currentPageItems.value.length; i += 4) {
    rows.push(currentPageItems.value.slice(i, i + 4));
  }
  return rows;
});
const placeOrder=async (foodItem)=>{
  const data = {
    totalamount: foodItem.allprice,
    packId: foodItem.id
  };


  const respone= await insertorderdetailByitempackservice(data)
  if(respone.code===200){
    types.value='success'
    title.value='下单成功！'
    showalret.value=!showalret.value
  await  alipayordertest(subject,foodItem,orderno)
    console.log('执行成功')
  }else {
    types.value='warning'
    title.value='您有订单未支付，请支付后再下单'
    showalret.value=!showalret.value
    console.log('执行失败')
  }


}
const itemdetail = async(foodItem)=> {
  await routers.push({
    path:'/orderfood/itempackdetail',
    query: {
      itemname: foodItem.description,
      imageUrl:foodItem.imageUrl,
      price:foodItem.allprice,
      id:foodItem.id
    }
  })

}
const generateOrderNumber=()=> {
  const timestamp = Date.now().toString(); // 当前时间戳
  const randomNum = Math.floor(Math.random() * 100000).toString().padStart(5, '0'); // 5位随机数
  const orderNumber = parseInt(`${timestamp}${randomNum.toString().padStart(5, '0')}`);
  orderno.value= orderNumber; // 将生成的订单号赋值给 traceNo
}
const alipayordertest=async (subject,foodItem,orderno)=>{
  await alipayorder(subject,foodItem,orderno)
}
const alipayorder=  (subject,foodItem,orderno)=>{
  const params =  new URLSearchParams({
    subject: subject,
    traceNo: orderno,
    totalAmount: foodItem.allprice,
  });
  window.location.href = `http://lsyspringboot.natapp1.cc/alipay/pay?${params.toString()}`;
}
</script>

<style scoped>
.card-row {
  display: flex;
  margin-bottom: 20px;
}

.card-item {
  max-width: 200px;
  margin-right: 20px;
  flex-basis: 25%;
}
.card-price{
  color: red;
}
.card-img {
  width: 100%;
  height: 150px; /* 固定高度 */
  object-fit: cover; /* 确保图片按比例缩放，覆盖整个区域 */
}
</style>